package com.starblink.store.memanage.vm

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.rocketreserver.FetchMySubscribeMerchantWebQuery
import com.starblink.rocketreserver.fragment.MerchantWebVOF
import com.starblink.store.recommend.ui.RecommendStoreVM
import kotlinx.coroutines.launch

class MeManageVM : RecommendStoreVM() {
    var subscribePageNo = 1
    var isAutoLoadMore = false//订阅店铺自动加载中

    var subscribeList: MutableLiveData<MutableList<MerchantWebVOF>> =
        MutableLiveData(mutableListOf())
    var subHasNext: MutableLiveData<Boolean> = MutableLiveData()

    fun initRefresh() {
        fetchMySubscribeMerchantWeb(true, false)
    }

    //我的-顶部订阅店铺数据
    fun fetchMySubscribeMerchantWeb(showLoading: Boolean = false, initRefresh: Boolean = false) {
        if (initRefresh) {
            subscribePageNo = 1
            isAutoLoadMore = false
        }
        viewModelScope.launch {
            val response = SkGqlClient.skQuery(
                FetchMySubscribeMerchantWebQuery(
                    subscribePageNo,
                    100,//pageSize不能随意改动，adapter根据长度自动加载更多
                ), showDefaultLoading = showLoading && myPageNo == 1
            )
            isAutoLoadMore = false
            response?.data?.fetchMySubscribeMerchantWeb?.subList?.map { it.merchantWebVOF }
                ?.let { list ->
                    if (initRefresh) {
                        subscribeList.value!!.clear()
                    }
                    subscribeList.value!!.addAll(list)
                    subscribeList.value = subscribeList.value
                    subHasNext.postValue(response.data!!.fetchMySubscribeMerchantWeb.hasNext)

                    if (subscribeList.value!!.isNotEmpty() && list.size == 20) {
                        subscribePageNo++
                    }
                }
        }
    }


    //其它地方订阅店铺 同步增加
    fun addSubscribeStore(merchant: MerchantWebVOF) {
        subscribeList.value?.add(merchant)
        subscribeList.value = subscribeList.value
    }
}